package com.xiaoman.international.util;

import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.stream.Collectors;

public class ReflectUtil {

    public static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        final Field field = getField((obj instanceof Class) ? (Class<?>) obj : obj.getClass(), fieldName);
        setFieldValue(obj, field, value);
    }

    private static Field getField(Class<?> aClass, String fieldName) throws NoSuchFieldException {
        try {
            return Arrays.stream(getAllDeclareFields(aClass)).collect(Collectors.toMap(Field::getName, e -> e)).get(fieldName);
        } catch (Exception e) {
            throw new NoSuchFieldException();
        }
    }

    public static void setFieldValue(Object obj, Field field, Object value) throws IllegalAccessException {
        field.setAccessible(true);
        field.set(obj,value);
    }

    public static Object getFieldValue(Object obj, Field field) throws IllegalAccessException {
        field.setAccessible(true);
        return field.get(obj);
    }


    private static Field[] getAllDeclareFields(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        while (!((clazz = clazz.getSuperclass()).equals(Object.class)))
            fields = ArrayUtils.addAll(fields, clazz.getDeclaredFields());
        return fields;
    }
}
